﻿/*******************************************************************************
 * Copyright @ 2017 YunSpace.Framework 版权所有
 * Author: GaoTang
 * Description: YunSpace 快速开发平台
 * Website：http://www.yunspace.com.cn
*********************************************************************************/
#region USING SYSTEM
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web.Mvc;
using YunSpace.Application.OrderFlowManage;
using YunSpace.Application.SiteLibraryManage;
using YunSpace.Application.SiteMgr;
using YunSpace.Application.WorkFlow;
using YunSpace.Core;
using YunSpace.Domain.Entity.OrderFlowManage;
using YunSpace.Domain.Entity.SiteMgr;
using YunSpace.Domain.ViewModel;
using YunSpace.Domain.ViewModel.OrderFlowManage;
using YunSpace.Domain.ViewModel.Sale;
using YunSpace.Domain.ViewModel.WorkFlow;
using YunSpace.ThirdService;
#endregion

namespace YunSpace.Web.Areas.OrderFlowManage.Controllers
{
    /// <summary>
    /// 客户订单流程
    /// </summary>
    public class ClientOrderController : ControllerBase
    {
        private ClientOrderApp clientOrderApp = new ClientOrderApp();
        private ClientInfosApp clientInfosApp = new ClientInfosApp();
        private FlowManageApp flowManageApp = new FlowManageApp();
        private SiteOrderSalesReportApp salesReportApp = new SiteOrderSalesReportApp();
        private ClientReturnvisitrecordApp clientReturnvisitrecordApp = new ClientReturnvisitrecordApp();
        private string LoginProvider = Configs.GetValue("LoginProvider");
        private string LoginUserKey = "YunSpace_loginuserkey_2016";
        private string PhotoUrl = "http://storage.yunspace.com.cn/";

        #region 0001. Common

        public string RandomNo
        {
            get
            {
                return DateTime.Now.ToString("yyyyMMddhhmmss");
            }
        }

        /// <summary>
        /// 获取数据集合
        /// </summary>
        /// <param name="keyValue">查询条件</param>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetItemsJson()
        {
            var data = new
            {
                Units = clientOrderApp.GetItemList("units"),                // 价格单位
                City = clientOrderApp.GetAllCitys(),                        // 城市
                //Areas = clientInfosApp.GetAllAreas(),                     // 区域
                //BusinessAreas = clientInfosApp.GetAllBusinessAreas(),     // 商圈
                ActivityType = clientOrderApp.GetItemList("ActivityType"),  // 活动类型
                FirstActivityType = clientOrderApp.GetItemList("FirstActivityType"),
                SiteType = clientOrderApp.GetItemList("SiteType"),          // 场地类型
                Position = clientOrderApp.GetItemList("gszw"),              // 公司职位
                Department = clientOrderApp.GetItemList("bmmc"),            // 所属部门
                fylm = clientInfosApp.GetItemList("fylm")                   // 费用类型
            };

            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetCitysJson()
        {
            var data = clientOrderApp.GetAllCitys();
            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetAreasJson(string parentIds = "")
        {
            var data = clientOrderApp.GetAllAreas(parentIds);
            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetAreasByParentIdJson(string areaId)
        {
            var data = clientOrderApp.GetAreasByParentId(areaId);
            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetBusinessAreasJson(string parentIds = "")
        {
            var data = clientOrderApp.GetAllBusinessAreas(parentIds);
            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetItemJson(string enCode)
        {
            // ServicesCost 配套服务
            var data = clientOrderApp.GetItemList(enCode);
            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJson(string keyValue)
        {
            var data = clientOrderApp.GetForm(keyValue);
            return Content(data.ToJson());
        }

        /// <summary>
        /// 提交表单
        /// </summary>
        /// <param name="clientOrderEntity">表单实体</param>
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitForm(ClientOrderEntity clientOrderEntity, string keyValue)
        {
            clientOrderApp.SubmitForm(clientOrderEntity, keyValue);

            return Success("操作成功。");
        }

        /// <summary>
        /// 删除表单
        /// </summary>
        /// <param name="keyValue">表单主键</param>
        [HttpPost]
        [HandlerAjaxOnly]
        [HandlerAuthorize]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteForm(string keyValue)
        {
            clientOrderApp.DeleteForm(keyValue);

            return Success("删除成功。");
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetToken()
        {
            var data = new
            {
                token = QiniuHelper.Instance.GetToken()
            };
            return Content(data.ToJson());
        }

        #endregion

        #region 1001. 我的订单列表

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJson(Pagination pagination, string queryJson)
        {
            var environment = Request.QueryString["environment"];
            var type = Request.QueryString["type"];
            var data = new
            {
                rows = clientOrderApp.GetList(pagination, queryJson, type, environment),
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };

            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetCloseOrderGridJson(Pagination pagination, string queryJson)
        {
            //var environment = Request.QueryString["environment"];
            //var type = Request.QueryString["type"];
            var data = new
            {
                rows = clientOrderApp.GetCloseOrderList(pagination, queryJson),
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };

            return Content(data.ToJson());
        }



        /// <summary>
        /// 让单[Index.cshtml]
        /// </summary>
        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ShowGiveSingle()
        {
            return View();
        }

        /// <summary>
        /// 用户与部门相关表
        /// </summary>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetDeptByUsersJson()
        {
            var data = clientOrderApp.GetDeptByUsers();
            return Content(data.ToJson());
        }

        [HttpGet]
        public ActionResult GetDeptByUsersByDeptId(string deptId)
        {
            var data = clientOrderApp.GetDeptByUsersByDeptId(deptId);
            return Content(data.ToJson());
        }

        /// <summary>
        /// 添加用户订单
        /// </summary>
        /// <param name="deptByUserEntity"></param>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitDeptByUsers(DeptByUserViewModel deptByUserEntity, string keyValue)
        {
            var isSignOut = clientOrderApp.SubmitDeptByUsers(deptByUserEntity, keyValue);

            return isSignOut ? Success("操作成功。") : Error("此订单已让单过一次，不能再次让单！");
        }

        /// <summary>
        /// 转让订单
        /// </summary>
        /// <param name="deptByUserEntity"></param>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitOrderDeptByUsers(DeptByUserViewModel deptByUserEntity, string keyValue)
        {
            //var isSignOut = clientOrderApp.SubmitOrderDeptByUsers(deptByUserEntity, keyValue);
            clientOrderApp.SubmitOrderDeptByUsers(deptByUserEntity, keyValue);
            //return isSignOut ? Success("操作成功。") : Error("此订单已让单过一次，不能再次让单！");
            return Success("操作成功。");
        }
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitBaseDemandForm(OrderInfoInput orderInfo, string keyValue)
        {
            clientOrderApp.SubmitBaseDemandForm(orderInfo, keyValue);

            return Success("更新需求成功。");
        }

        /// <summary>
        /// 获取所有相关订单提示内容
        /// </summary>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetCheckRecordTodoJson(string pageType)
        {
            var data = clientOrderApp.GetCheckRecordTodo(pageType);
            return Content(data.ToJson());
        }

        /// <summary>
        /// 用户与部门相关表
        /// </summary>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetOrderTagsJson(string orderId)
        {
            var data = clientOrderApp.GetOrderTags(orderId);
            return Content(data.ToJson());
        }

        #endregion

        #region 2001. 订单资料

        /// <summary>
        /// 获取我的订单的详细数据
        /// </summary>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetOrderInfoJson(string keyValue, string isread = "")
        {
            var data = clientOrderApp.GetOrderInfo(keyValue, isread);
            return Content(data.ToJson());
        }

        /// <summary>
        /// 关闭订单 [Details.cshtml]
        /// </summary>
        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ShowOrderClose()
        {
            return View();
        }

        /// <summary>
        /// 关闭订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CloseOrder(string orderId)
        {
            clientOrderApp.CloseOrder(orderId);
            return Success("成功");
        }


        [HttpGet]
        public ActionResult OrderReportList()
        {
            return View();
        }

        #endregion

        #region 2002. 流程流转

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetOrderCheckRecordList(string orderId)
        {
            var data = new
            {
                rows = clientOrderApp.GetOrderCheckRecordList(orderId)
            };

            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetOrderRecommendList(string orderId)
        {
            var data = new
            {
                rows = clientOrderApp.GetOrderRecommendList(orderId)
            };

            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetOrderTakelookList(string orderId)
        {
            var data = new
            {
                rows = clientOrderApp.GetOrderTakelookList(orderId)
            };

            return Content(data.ToJson());
        }


        #endregion

        #region 2003. 推荐场地

        /// <summary>
        /// 推荐场地 查询分页
        /// </summary>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetSiteGridJson(Pagination pagination, string queryJson)
        {
            var data = new
            {
                rows = clientOrderApp.GetSiteList(pagination, queryJson),
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };

            return Content(data.ToJson());
        }

        ///// <summary>
        ///// 确认场地 [SaveSite.cshtml]
        ///// </summary>
        //[HttpGet]
        //[HandlerAuthorize]
        //public ActionResult SaveSite()
        //{
        //    return View();
        //}

        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ShowSendSite()
        {
            return View();
        }

        /// <summary>
        /// 推荐场地
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="orderIds"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitSendSiteForm(OrderSitesFlowInput orderRecommendEntity, string keyValue)
        {
            var No = this.RandomNo;
            var isContainSite = clientOrderApp.SendSite(No, orderRecommendEntity);
            if (isContainSite)
            {
                flowManageApp.CreateFlowRecord(new CreateFlowInput
                {
                    RandomNo = No,
                    OrderId = keyValue,
                    FlowFormId = orderRecommendEntity.FlowFormId,
                    FlowState = 1
                });
                return Success("操作成功。");
            }
            else
            {
                //this.FileLog.Info("您推荐的场地-空间有已推荐过的，请重新选择。");
                return Error("您推荐的场地-空间有已推荐过的，请重新选择。");
            }
        }

        /// <summary>
        /// 推荐场地（跳转带看场地）
        /// </summary>
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitSendSiteFlowForm(string keyValue)
        {
            clientOrderApp.SendSiteFlow(keyValue);

            return Success("操作成功。");
        }

        #region 发送邮件和短信
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SendSpaceEmail(string SpaceIds, string ToEmail, string Contact, string ActivityName, string Phone)
        {
            OperatorModel operatorModel = new OperatorModel();
            if (LoginProvider == "Cookie")
            {
                operatorModel = DESEncrypt.Decrypt(WebHelper.GetCookie(LoginUserKey).ToString()).ToObject<OperatorModel>();
            }
            else
            {
                operatorModel = DESEncrypt.Decrypt(WebHelper.GetSession(LoginUserKey).ToString()).ToObject<OperatorModel>();
            }
            RongLianSmsManger sms = new RongLianSmsManger();
            MailHelper mail = new MailHelper();
            mail.MailServer = Configs.GetValue("MailHost");
            mail.MailUserName = operatorModel.Email;
            mail.MailPassword = operatorModel.EmailPassword;
            if (String.IsNullOrEmpty(mail.MailPassword))
                return Error("您未设置邮箱密码");
            mail.MailName = operatorModel.UserName;
            //获取模板
            var TempName = Configs.GetValue("SiteFlowEmail");

            //获取城市集合
            ClientInfosApp clientInfosApp = new ClientInfosApp();
            var CityArr = clientInfosApp.GetAllCitys();

            var guid = Guid.NewGuid().ToString("N");
            var SpaceIdArray = SpaceIds.Split(',');
            var Attachment = new List<string>();
            var BodyList = new List<string>();
            var LoginName = operatorModel.UserName;
            var MobilePhone = operatorModel.MobilePhone;
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (string item in SpaceIdArray)
            {
                var SiteId = item.Split('|')[0];
                var SpaceId = item.Split('|')[1];

                SiteApp siteApp = new SiteApp();
                var site = siteApp.GetSite(SiteId);
                SpaceApp spaceApp = new SpaceApp();
                var Space = spaceApp.GetForm_Mini(SpaceId);

                var Max = Space.max_seating_capacity == null ? "" : Space.max_seating_capacity.ToString();//最大容纳人数
                var address = site.address;//地址
                var area = Space.area == null ? "" : Space.area.ToString();//使用面积
                var height = Space.height == null ? "" : Space.height.ToString();//空间层高
                var accept_weight = Space.accept_weight;//最大承重
                var site_type = site.site_type;//场地类型
                var PPTpath = site.F_AttachmentPpt;
                var Photo = spaceApp.GetPhoto(SpaceId);

                BodyList.Add(InitEmailBody(PhotoUrl + Photo[0].F_path, site.title, address, area, Max, height, accept_weight, site_type));
                var CityName = CityArr.Find(a => a.F_Id == site.city_id).F_FullName;
                if (dic.ContainsKey(CityName))
                {
                    dic[CityName] += "," + site.title;
                }
                else
                {
                    dic.Add(CityName, site.title);
                }

                //下载ppt
                if (!String.IsNullOrEmpty(ToEmail))
                {
                    string _toSavePdfDirectory = AppDomain.CurrentDomain.BaseDirectory;
                    var fileName = PPTpath.Substring(PPTpath.LastIndexOf("/"));
                    var path = $"{_toSavePdfDirectory}\\PPT\\{DateTime.Now:yyyyMMdd}\\{guid}\\";

                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    WebHelper.Download(PPTpath, path + fileName);
                    Attachment.Add(path + fileName);
                }
            }
            StringBuilder sb = new StringBuilder();
            foreach (var item in dic)
            {
                sb.Append(item.Key + "的" + item.Value + ",");
            }
            string Address = sb.ToString();
            Address = Address.Substring(0, Address.Length - 1);

            var EmailBool = false;
            //发送邮件
            if (!String.IsNullOrEmpty(ToEmail))
            {
                //读取邮件模板
                var EmailBody = mail.GetMainBody(TempName);
                //替换模板的推荐地址
                EmailBody = EmailBody.Replace("{{Address}}", Address);
                //替换模板的活动名称
                EmailBody = EmailBody.Replace("{{ActivityName}}", ActivityName);
                //替换模板的内容
                EmailBody = EmailBody.Replace("{{Body}}", String.Join("", BodyList));
                //替换介绍人
                EmailBody = EmailBody.Replace("{{Name}}", Contact);
                EmailBody = EmailBody.Replace("{{LoginName}}", LoginName);
                EmailBody = EmailBody.Replace("{{LoginPhone}}", MobilePhone);
                EmailBool = mail.SendToAttachment(ToEmail, "YUNSPACE场地推荐", EmailBody, String.Join(",", Attachment));
            }

            //发送短信       
            if (!String.IsNullOrEmpty(Phone))
            {
                var smsData = new String[] { Contact, ActivityName, Address, LoginName, MobilePhone };
                sms.SendSiteFlowInfo(Phone, smsData);
            }
            if (EmailBool)
                return Success("发送成功");
            else
                return Error("邮件发送失败");
        }

        private string InitEmailBody(string url, string name, string address, string area, string Max, string height, string accept_weight, string site_type)
        {
            string str = string.Format(@"<div style = 'position: relative;border-bottom: solid 1px #2B75BB;overflow: hidden;padding: 20px 0;'>
                         <div style = 'height: 100%;position: absolute;background: #eee;z-index: -1;'></div>
                          <div style = 'padding: 15px 10px;'>   
                               <img style = 'z-index:999;float: left;width: 400px;height:200px;' src = '{0}' title = '没图片' />
                                    <div style = 'float: left;width: 48%;padding-left: 2%;'>
                                         <p>{1}</p>
                                            <p style = 'border:1px solid #D8D8D8;'></p>
                                             <div style = 'font-size: 12px;color: #4A4A4A;'>
                                                  <p> 地理位置: {2} </p>
                                                       <p> 使用面积: {3}</p>
                                                          <p> 容纳人数: {4}人 </p>
                                                             <p> 空间层高: {5} </p>
                                                                <p> 空间承重: {6}</p>
                                                                   <p> 场地类型: {7} </p>
                                                                  </div>
                                                              </div>
                                                          </div>
                                                      </div>", url, name, address, area, Max, height, accept_weight, site_type);
            return str;
        }
        #endregion



        #endregion

        #region 2004. 带看场地

        #region 200401 带看场地列表

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetTakelookDetailJson(string orderId)
        {
            var data = new
            {
                rows = clientOrderApp.TakelookDetail(orderId),
            };
            return Content(data.ToJson());
        }


        /// <summary>
        /// 客户场地带看 查询分页
        /// </summary>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetSendSiteGridByTakelookJson(string orderId)
        {
            var data = new
            {
                rows = clientOrderApp.GetSendSiteGridByTakelookJson(orderId),
            };

            return Content(data.ToJson());
        }

        #endregion

        #region 200402 带看场地列表中的按钮操作

        /// <summary>
        /// 预约
        /// </summary>
        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ShowPreviewService()
        {
            return View();
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitPreviewForm(OrderTakelookDetailInput orderTakelookEntity, string keyValue)
        {

            var isNoAdd = clientOrderApp.SubmitPreviewTimeForm(orderTakelookEntity.Time, keyValue);
            if (isNoAdd)
            {
                clientOrderApp.SubmitPreviewCarForm(orderTakelookEntity.Car, keyValue);
                clientOrderApp.SubmitPreviewPeopleForm(orderTakelookEntity.People, keyValue);
            }

            return isNoAdd ? Success("操作成功。") : Error("已添加过相关场地空间的带看记录。");
        }

        /// <summary>
        /// 预约时间
        /// </summary>
        [HttpGet]
        [HandlerAuthorize]
        public ActionResult PreviewTime()
        {
            return View();
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitPreviewTimeForm(OrderTakelookDetailTimeInput orderTakelookTimeEntity, string keyValue)
        {
            var isNoAdd = clientOrderApp.SubmitPreviewTimeForm(orderTakelookTimeEntity, keyValue);

            return isNoAdd ? Success("操作成功。") : Error("同一个场地最多只能添加一个预约时间。");
        }

        ///// <summary>
        ///// 预约车辆
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet]
        //[HandlerAuthorize]
        //public ActionResult PreviewCar()
        //{
        //    return View();
        //}


        //[HttpPost]
        //[HandlerAjaxOnly]
        //[ValidateAntiForgeryToken]
        //public ActionResult SubmitPreviewCarForm(OrderTakelookDetailCarInput orderTakelookCarEntity, string keyValue)
        //{
        //    clientOrderApp.SubmitPreviewCarForm(orderTakelookCarEntity, keyValue);

        //    return Success("操作成功。");
        //}

        ///// <summary>
        ///// 预约陪同人员
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet]
        //[HandlerAuthorize]
        //public ActionResult PreviewPeople()
        //{
        //    return View();
        //}

        //[HttpPost]
        //[HandlerAjaxOnly]
        //[ValidateAntiForgeryToken]
        //public ActionResult SubmitPreviewPeopleForm(OrderTakelookDetailPeopleInput orderTakelookPeopleEntity, string keyValue)
        //{
        //    clientOrderApp.SubmitPreviewPeopleForm(orderTakelookPeopleEntity, keyValue);

        //    return Success("操作成功。");
        //}
        #endregion

        #region 200403 带看预约清单 按钮

        /// <summary>
        /// 申请 带看预约清单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ShowTakelook()
        {
            return View();
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetTakelookJson(string orderId)
        {
            var data = new
            {
                rows = clientOrderApp.GetRecommendByTakelookList(orderId),
            };
            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetTakelookFeelbackJson(string orderId)
        {
            var data = new
            {
                rows = clientOrderApp.GetRecommendByTakelookFeelbackList(orderId),
            };
            return Content(data.ToJson());
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitTakelookForm(OrderSitesFlowInput orderTakelookEntity, string keyValue)
        {
            var exist = clientOrderApp.SubmitTakelookForm(orderTakelookEntity, keyValue);
            if (exist)
            {
                flowManageApp.CreateFlowRecord(new CreateFlowInput
                {
                    RandomNo = orderTakelookEntity.No,
                    OrderId = keyValue,
                    FlowFormId = orderTakelookEntity.FlowFormId,
                    FlowState = 2
                });
                return Success("操作成功。");
            }
            else
            {
                return Error("此批次的场地已申请过带看，请确认后重试。");
            }
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitTakelookFeelbackForm(OrderTakelookFeelbackInput orderTakelookFeelbackEntity, string keyValue)
        {
            var exist = clientOrderApp.SubmitTakelookFeelback(orderTakelookFeelbackEntity, keyValue);
            if (exist)
            {
                //flowManageApp.CreateFlowRecord(new CreateFlowInput
                //{
                //    RandomNo = No,
                //    OrderId = keyValue,
                //    FlowFormId = orderTakelookFeelbackEntity.FlowFormId,
                //    FlowState = 3
                //});
                return Success("操作成功。");
            }
            else
            {
                return Error("此批次的场地已反馈，请确认后重试。");
            }
        }

        [HttpGet]
        [HandlerAjaxOnly]
        /// <summary>
        /// 获取默认的带看分配人员
        /// </summary>
        public ActionResult GetTakelookAllotUserJson()
        {

            var data = new
            {
                user = Configs.GetValue("ClientOrder.User").ToObject(),
                dept = Configs.GetValue("ClientOrder.Dept").ToObject()
            };
            return Content(data.ToJson());
        }


        #endregion

        #region 200404 退回上一流程

        /// <summary>
        /// 带看场地（回退到推荐场地）
        /// </summary>
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult BackSendSiteFlowForm(string keyValue)
        {
            clientOrderApp.BackSendSiteFlow(keyValue);

            return Success("操作成功。");
        }

        #endregion

        #region 200405 带看反馈

        /// <summary>
        /// 申请 带看反馈
        /// </summary>
        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ShowTakelookFeedback()
        {
            return View();
        }

        #endregion

        #endregion

        #region 2005. 意向场地确认

        #region 200501 加载列表

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetTakelookGridByIntentionSiteJson(string orderId)
        {
            var data = new
            {
                rows = clientOrderApp.GetTakelookGridByIntentionSiteJson(orderId),
            };

            return Content(data.ToJson());
        }

        #endregion

        #region 200502 流程流转

        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitIntentionSiteForm(OrderSitesFlowInput intentionEntity, string keyValue)
        {
            var exists = clientOrderApp.IntentionSite(intentionEntity, keyValue);
            if (exists)
            {
                flowManageApp.CreateFlowRecord(new CreateFlowInput
                {
                    RandomNo = intentionEntity.No,
                    OrderId = keyValue,
                    FlowFormId = intentionEntity.FlowFormId,
                    FlowState = 3 // 状态3 意向场地确认不需要审核
                });

                return Success("操作成功。");
            }
            else
            {
                return Error("此批次的场地已申请过报价。");
            }
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitIntentionSiteFlowForm(string keyValue)
        {
            clientOrderApp.IntentionSiteFlow(keyValue);

            return Success("操作成功。");
        }

        #endregion

        #region 200503 配套服务

        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ShowIntentionService()
        {
            return View();
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetIntentionDetailJson(string orderId)
        {
            var data = new
            {
                rows = clientOrderApp.IntentionDetail(orderId),
            };
            return Content(data.ToJson());
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitIntentionServiceForm(IntentionDetailInput entity, string keyValue)
        {
            clientOrderApp.SubmitIntentionForm(entity.Data, keyValue);

            return Success("操作成功。");
        }


        [HttpPost]
        [HandlerAjaxOnly]
        [HandlerAuthorize]
        //[ValidateAntiForgeryToken]
        public ActionResult DeleteIntentionServiceForm(string keyValue)
        {
            clientOrderApp.DeleteIntentionDetailForm(keyValue);

            return Success("删除成功。");
        }

        #endregion

        #endregion

        #region 2006 价格审核

        #region 200601 加载列表

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetIntentionSiteGridByPriceTalksJson(string orderId)
        {
            var data = new
            {
                rows = clientOrderApp.GetIntentionSiteGridByPriceTalksJson(orderId),
            };

            return Content(data.ToJson());
        }

        #endregion

        #region 200602 流程流转

        ///// <summary>
        ///// 场地报价单申请
        ///// </summary>
        //[HttpPost]
        //[HandlerAjaxOnly]
        //public ActionResult ApplyPriceTalksFlowForm(OrderSitesFlowInput entity, string keyValue)
        //{
        //    var No = this.RandomNo;
        //    var exists = clientOrderApp.CreatePriceTalksFlow(No, entity, keyValue);
        //    if (exists)
        //    {
        //        flowManageApp.CreateFlowRecord(new CreateFlowInput
        //        {
        //            RandomNo = No,
        //            OrderId = keyValue,
        //            FlowFormId = entity.FlowFormId,
        //            FlowState = 4
        //        });

        //        return Success("操作成功。");
        //    }
        //    else
        //    {
        //        return Error("部分场地已申请过报价，请确认后再申请。");
        //    }
        //}

        /// <summary>
        /// 发送报价单
        /// </summary>
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitPriceTalksFlowForm(OrderSitesFlowInput entity, string keyValue)
        {
            var exists = clientOrderApp.SubmitPriceTalksFlow(entity, keyValue);

            if (exists)
            {
                flowManageApp.CreateFlowRecord(new CreateFlowInput
                {
                    RandomNo = entity.No,
                    OrderId = keyValue,
                    FlowFormId = entity.FlowFormId,
                    FlowState = 4
                });
                return Success("发送报价单成功。");
            }
            else
            {
                return Error("已发送相关的报价单，请确认后重试。");
            }
        }

        #endregion

        #region 200603 配套服务

        //[HttpGet]
        //[HandlerAuthorize]
        //public ActionResult ShowPriceTalks()
        //{
        //    return View();
        //}

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetPriceTalksJson(string orderId, string siteId, string spaceId)
        {
            var data = new
            {
                rows = clientOrderApp.GetPriceDetail(orderId, siteId, spaceId),
            };
            return Content(data.ToJson());
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitPriceTalksForm(ClientOrderPriceDetailEntity entity, string keyValue)
        {
            clientOrderApp.SubmitPriceTalksForm(entity, keyValue);

            return Success("操作成功。");
        }

        #endregion

        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ShowPriceDetail()
        {
            return View();
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetPriceDetailJson(string keyValue, string siteId, string spaceId)
        {

            var data = new
            {
                rows = clientOrderApp.GetPriceDetailList(keyValue, siteId, spaceId)
            };
            return Content(data.ToJson());
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitPriceDetailForm(OrderPriceDetailInput entity, string keyValue)
        {
            // 修改报价单
            clientOrderApp.SubmitPriceDetail(entity);
            return Success("操作成功。");
            //var No = this.RandomNo;
            //var exists = clientOrderApp.SubmitPriceTalksFlow(No, keyValue);

            //if (exists)
            //{
            //    flowManageApp.CreateFlowRecord(new CreateFlowInput
            //    {
            //        RandomNo = No,
            //        OrderId = keyValue,
            //        FlowFormId = entity.FlowFormId,
            //        //FlowState = 5
            //        FlowState = 4
            //    });

            //    return Success("操作成功。");
            //}
            //else
            //{
            //    return Error("已发送相关的报价单，请确认后重试。");
            //}
        }

        #endregion

        #region 2007 场地预定

        #region 200701 加载列表

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetPriceTalksGridByReserveSiteJson(string orderId)
        {
            var data = new
            {
                rows = clientOrderApp.GetPriceTalksGridByReserveSiteJson(orderId),
            };

            return Content(data.ToJson());
        }

        #endregion

        #region 200702 流程流转

        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitReserveSiteFlowForm(OrderSitesFlowInput entity, string keyValue)
        {
            var exists = clientOrderApp.SubmitReserveSiteForm(entity, keyValue);

            if (exists)
            {
                flowManageApp.CreateFlowRecord(new CreateFlowInput
                {
                    RandomNo = entity.No,
                    OrderId = keyValue,
                    FlowFormId = entity.FlowFormId,
                    //FlowState = 6
                    FlowState = 5
                });

                return Success("操作成功。");
            }
            else
            {
                return Error("部分场地已预定过，请确认后重试。");
            }
        }

        #endregion

        #endregion

        #region 2008 用印申请

        #region 200801 加载列表
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetImpressGridByReserveSiteJson(string orderId)
        {
            var data = new
            {
                rows = clientOrderApp.GetImpressGrid(orderId),
            };

            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetReserveSiteByOrderJson(string orderId)
        {
            var data = new
            {
                rows = clientOrderApp.GetReserveSiteByOrder(orderId),
            };

            return Content(data.ToJson());
        }
        #endregion

        #region 订单收付款处理
        [HttpGet]
        [HandlerAuthorize]
        public ActionResult OrderCashIndex()
        {
            return View();
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetOrderCashGridJson(Pagination pagination, string queryJson)
        {
            var data = new
            {
                rows = clientOrderApp.GetCashByOrder(pagination, queryJson),
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };

            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult UpdateCashState(string keyValue, int state, string Ino)
        {
            int exists = clientOrderApp.UpdateCashState(keyValue, state, Ino);

            if (exists == 1)
            {
                return Success("操作成功。");
            }
            else
            {
                return Error("操作失败，请联系相关工作人员。");
            }
        }


        #endregion
        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ShowImpress()
        {
            return View();
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitImpressForm(OrderImpressInput entity, string keyValue)
        {
            var No = this.RandomNo;
            var exists = clientOrderApp.SubmitImpressForm(No, entity, keyValue);

            if (exists)
            {
                flowManageApp.CreateFlowRecord(new CreateFlowInput
                {
                    RandomNo = No,
                    OrderId = keyValue,
                    FlowFormId = entity.FlowFormId,
                    //FlowState = 7
                    FlowState = 6
                });

                return Success("操作成功。");
            }
            else
            {
                return Error("您已申请过了，请联系相关工作人员。");
            }
        }

        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ShowClientUploader()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ShowSiteUploader()
        {
            return View();
        }

        public ActionResult CheckFileForm(string orderId)
        {
            var Check=clientOrderApp.GetFileExist(orderId);
            if (!Check)
                return Success("");
            else
                return Error("有合同未上传");
        }

        #endregion

        #region 2009 签订合同

        #region 200901 加载列表

        [HttpGet]
        [HandlerAuthorize]
        public ActionResult Uploader()
        {
            return View();
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetReserveSiteGridBySignContractJson(string orderId)
        {
            var data = new
            {
                rows = clientOrderApp.GetReserveSiteGridBySignContractJson(orderId)
            };

            return Content(data.ToJson());
        }

        #endregion

        #region 200902 流程流转

        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitSignContractFlowForm(OrderSitesFlowInput entity, string keyValue)
        {
            var fileExists = clientOrderApp.GetFileExistSignContract(entity.OrderId, entity.No);
            if (fileExists)
            {
                var exists = clientOrderApp.SubmitSignContractForm(entity, keyValue);

                if (exists)
                {
                    flowManageApp.CreateFlowRecord(new CreateFlowInput
                    {
                        RandomNo = entity.No,
                        OrderId = keyValue,
                        FlowFormId = entity.FlowFormId,
                        //FlowState = 8
                        FlowState = 7
                    });

                    return Success("操作成功。");
                }
                else
                {
                    return Error("您已经提交过相关的合同，请联系相关人员。");
                }
            }

            return Error("请先上传相关的合同文件。");
        }

        /// <summary>
        /// 文件上传生成合同，状态为-1
        /// </summary>
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitFileForm(UpdateSignContractFileInput entity, string keyValue)
        {
            clientOrderApp.SubmitFileSignContract(entity, keyValue);
            return Success("操作成功。");
        }

        /// <summary>
        /// 文件上传生成合同，状态为-1
        /// </summary>
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitClientFileForm(UpdateSignContractFileInput entity, string keyValue)
        {
            clientOrderApp.SubmitClientFileImpress(entity, keyValue); // 用印申请中的上传合同
            return Success("操作成功。");
        }

        /// <summary>
        /// 文件上传生成合同，状态为-1
        /// </summary>
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitSiteFileForm(UpdateSignContractFileInput entity, string keyValue)
        {
            clientOrderApp.SubmitSiteFileImpress(entity, keyValue); // 用印申请中的上传合同
            return Success("操作成功。");
        }
        #endregion

        #endregion

        #region 3001 公海（HighSeas）

        /// <summary>
        /// 公海
        /// </summary>
        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ShowHighSeas()
        {
            return View();
        }

        /// <summary>
        /// 踢单
        /// </summary>
        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ShowSignOutSingle()
        {
            return View();
        }

        /// <summary>
        /// 踢单、关闭订单
        /// </summary>
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitSignOutClientOrderForm(ClientOrderchangerecordEntity entity, string keyValue)
        {
            clientOrderApp.SignOutClientOrder(entity, keyValue);

            return Success("踢单成功。");
        }

        /// <summary>
        /// 踢单
        /// </summary>
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitSignInClientOrderForm(string keyValue)
        {
            clientOrderApp.SignInClientOrder(keyValue);

            return Success("接单成功。");
        }

        #endregion

        #region 客服回访记录

        /// <summary>
        /// 客服回访记录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ReturnVisitRecord()
        {
            return View();
        }

        /// <summary>
        /// 获取客服回访记录
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetReturnVisitRecordGridJson(Pagination pagination, string queryJson)
        {
            var environment = Request.QueryString["environment"];
            var type = Request.QueryString["type"];
            var data = new
            {
                rows = clientOrderApp.GetReturnVisitList(pagination, queryJson, type),
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };

            return Content(data.ToJson());
        }

        /// <summary>
        /// 回访记录弹窗
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize]
        public ActionResult ShowReturnVisit()
        {
            return View();
        }

        /// <summary>
        /// 提交回访记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SubmitReturnVisit(ClientReturnvisitrecordEntity entity)
        {
            clientOrderApp.SubmitReturnVisit(entity);
            return Success("成功。");
        }

        #endregion 客服回访记录

        /// <summary>
        /// 已关闭过的无效订单
        /// </summary>
        [HttpGet]
        public ActionResult CloseOrderIndex()
        {
            return View();
        }
        #region 销售日报管理       
        public ActionResult OrderTrackingReportManager()
        {
            return View();
        }

        public ActionResult OrderTrackingReport()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SubmitReportForm(string orderId, string F_OrderStep, string F_Id, SiteOrderSalesReportModel salesreport)
        {
            salesReportApp.InsertEntity(orderId, F_OrderStep, F_Id, salesreport);
            return Success("操作成功。");
        }

        [HttpGet]
        public ActionResult GetSaleReportEntity(string F_Id)
        {
            var data = salesReportApp.GetSaleReportEntity(F_Id);
            return Content(data.ToJson());
        }

        [HttpGet]
        public ActionResult GetSaleReportGridData(Pagination pagination, string queryJson)
        {
            var data = new
            {
                rows = salesReportApp.GetSaleReportGridData(pagination, queryJson),
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };
            return Content(data.ToJson());
        }

        [HttpGet]
        public ActionResult GetSaleReportGridHistoryData(Pagination pagination, string queryJson)
        {
            var data = new
            {
                rows = salesReportApp.GetSaleReportGridHistoryData(pagination, queryJson),
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };
            return Content(data.ToJson());
        }
        #endregion

        #region 流程跳转
        public ActionResult OrderFlowTake()
        {
            return View();
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult SubmitTakeForm(string orderId,string flowtype,string siteSpace, OrderPriceInput input)
        {
            clientOrderApp.OrderFlowTake(orderId, siteSpace, flowtype,input);
            return Success("操作成功");
        }

        [HttpGet]
        public ActionResult GetCheckPrice(string siteSpace, string orderId)
        {
            var result = clientOrderApp.GetCheckPrice(siteSpace, orderId);
            return Content(result.ToJson());
        }
        #endregion
    }
}


